-- userManeger存储用户的信息,定期写入服务器
local skynet = require "skynet"
local redis = require "skynet.db.redis"
require "util"
require "User"
local CMD = {}

local users = {}
local usersOnline = {}

local db

local json = require "json"

local NPC
local function load_json_NPC()
    local f = assert(io.open("../json/NPC.json"), "Can't open file")
    local str = f:read "a"
    f:close()
    NPC = json.decode(str)
end

local function getNPCById(id)
    if NPC[id] == nil then
        return nil
    else
        return NPC[id]
    end
end

-- 根据名字查找fd
local fds = {}

function CMD.getUserByName(name)
    if users[name] == nil then
        return nil
    else
        return users[name]:__tostring()
    end
end

function CMD.getFdByName(name)
    print("find fd by name:" .. name)
    for k, v in pairs(fds) do
        print(k .. v)
    end
    return fds[name]
end

function CMD.getFds()
    local res = {}
    for i, v in ipairs(fds) do
        res[i] = v
    end
    return res
end

-- ！需写入数据库，新增一个user
function CMD.addUser(user)
    local username = user.username
    local password = user.password

    -- 查询用户名是否已注册
    if users[username] == nil then
        local user = User.new(username, password)
        users[username] = user
        print("user id " .. user.id)
        -- 写入数据库
        db:set("userMaxId_bysystem", user.id)
        db:set(username, user:__tostring())
        local usernames = db:get("usernames_bysystem")
        if usernames == "" then
            usernames = username
        else
            usernames = usernames .. "|" .. username
        end
        db:set("usernames_bysystem", usernames)

        -- 注册成功
        return {0, "注册成功"}
    else
        -- 已经被注册
        return {1, "账号重复!"}
    end
end

-- 玩家登录
function CMD.login(user)
    local username = user.username
    local password = user.password
    local fd = user.fd

    local code;
    local msg;
    local npc;

    if users[username] == nil then
        -- 用户不存在
        code = 1
        msg = 'User does not exist'
    else
        local user = users[username]
        local pwd = user.password
        if pwd == password then
            usersOnline[username] = true
            print("login save fd:" .. fd)
            fds[username] = fd
            -- 登录成功
            code = 0
            msg = 'Logged in'

            -- 读取NPC信息
            local id = user.id
            print("id:" .. id)
            npc = getNPCById(id)
            print(npc)
            for k, v in pairs(npc) do
                print(k)
                print(v)
            end
        else
            -- 密码错误
            code = 2
            msg = 'Wrong password'
        end
    end

    return {code, msg, user, npc}
end

-- 登出
function CMD.logout(user)
    local username = user.username or nil
    if username ~= nil then
        usersOnline[username] = nil
        fds[username] = nil
    end
end

-- 返回所有用户
function CMD.getUsers()
    local res = {}
    for k, v in pairs(users) do
        res[k] = k
    end
    return res
end

-- 返回所有在线用户
function CMD.getUsersOnline()
    local res = {}
    for k, v in pairs(usersOnline) do
        res[k] = k
    end
    return res
end

local function initUserMaxId()
    local userMaxId = db:get("userMaxId_bysystem")
    if userMaxId == nil then
        db:set("userMaxId_bysystem", 0)
    else
        User.maxId = tonumber(userMaxId)
    end
end

local function initUsers()
    local usernames = db:get("usernames_bysystem")
    if usernames == nil then
        db:set("usernames_bysystem", "")
    else
        -- 初始化
        usernames = split(usernames, "|")
        for i, name in ipairs(usernames) do
            local userString = db:get(name)
            local user = User:newByString(userString)
            users[user.username] = user
        end
    end
end

function CMD.start(conf)
    -- dbService = skynet.uniqueservice("dbService")
    -- db = skynet.call(dbService, "lua", "getDb")
    local redisConfig = {
        host = '127.0.0.1',
        port = 6379,
        db = 0
    }
    db = redis.connect(redisConfig)
    -- 读取数据库，维护用户maxId
    initUserMaxId()
    -- 读取数据库，恢复已经注册的用户
    initUsers()

    -- 读表
    load_json_NPC()
end

skynet.start(function()
    skynet.dispatch("lua", function(_, _, command, ...)
        local f = CMD[command]
        skynet.ret(skynet.pack(f(...)))
    end)
end)
